package cn.edu.njnu.opengmpback.Modeling.socket;

import cn.edu.njnu.opengmpback.common.nettywebsocket.annotations.WsServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import cn.edu.njnu.opengmpback.common.nettywebsocket.annotations.*;
import cn.edu.njnu.opengmpback.common.nettywebsocket.socket.Session;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.time.format.DateTimeFormatter;

/**
 * @Author TRY
 * @Date 2023/4/12 21:45
 * @Version 1.0
 */
@WsServerEndpoint(value = "/ComputeModelSocket/{projectId}/{userId}")
@Service
@Slf4j
public class ComputeModelSocket {
    private Session session;

    // session集合,存放对应的session
    private static ConcurrentHashMap<String, Map<String,Session>> sessionPool = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "projectId") String projectId, @PathParam(value = "userId") String userId) {
        sessionPool.putIfAbsent(projectId, new ConcurrentHashMap<>());
        Map<String,Session> sessions = sessionPool.get(projectId);
        sessions.put(userId, session);

        log.info("项目：{}, 加入连接,当前在线人数为：{}", projectId, sessions.size());
    }

    /**
     * 发生错误
     *
     * @param throwable e
     */
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();

    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose(@PathParam(value = "projectId") String projectId, @PathParam(value = "userId") String userId) {
        for (Map.Entry<String, Map<String,Session>> entry : sessionPool.entrySet()) {
            if (entry.getKey().equals(projectId)) {
                Map<String,Session> sessions = entry.getValue();
                sessions.remove(userId);
                log.info("项目：{}, 连接断开, 当前在线人数为：{}", entry.getKey(), entry.getValue().size());
            }
        }
    }

    /**
     * 接收客户端消息
     *
     * @param message 接收的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
//        log.info("收到客户端发来的消息：{}", message);

        try {
            JSONObject json = JSON.parseObject(message);

            String type = json.getString("type");

            if ("ping".equalsIgnoreCase(type)) {
                // 收到ping，回复pong
                String currentTime = java.time.LocalDateTime.now().format(
                        java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                );

//                String response = "Current Time: " + currentTime;
//                session.sendText(response);
            } else {
                // 处理其他消息逻辑
                log.info("处理其他消息类型: {}", type);
            }
        } catch (Exception e) {
            log.error("消息处理异常", e);
        }
    }

    /**
     * 推送消息到指定用户
     *
     * @param projectId  项目ID
     * @param message 发送的消息
     */
    public void sendMessageByProject(String projectId, String message) {
        log.info("项目：{}, 推送内容: {}", projectId, message);
        Map<String,Session> sessions = sessionPool.get(projectId);
        if (sessions != null) {
            for (Map.Entry<String, Session> map : sessions.entrySet()) {
                Session session = map.getValue();
                try {
                    session.sendText(message);  // 如果 session 已断开，这里不会抛异常但消息丢失
                } catch (Exception e) {
                    log.warn("发送失败，移除断开连接的用户：{}", map.getKey());
                    sessions.remove(map.getKey());
                }
            }
        }
    }
}
